<?php


namespace App\Core;


use App\Biquge\NovalJobHandler;
use App\Job\IJob;
use App\Job\QueueContract;
use App\Utils\Logger;

class Server
{

    protected $server;

    protected $config = [];

    protected $handler = NovalJobHandler::class;

    public function __construct(array $config)
    {
        $this->config = $config;
    }

    protected $events = array(
        'Receive' => 'onReceive',
        'ManagerStart' => 'onManagerStart',
        'Start' => 'onStart',
        'WorkerStart' => 'onWorkerStart',
        'Task' => 'onTask',
        'Finish' => 'onFinish',
    );

    final public function run(): void
    {
        $this->server = new \Swoole\Server('0.0.0.0', 9012);
        $this->server->set([
            'worker_num' => $this->config['worker_num'],
            'daemonize' => $this->config['daemonize'],
            'task_worker_num' => $this->config['task_worker_num'],
            'max_request' => 5000,
            'task_max_request' => $this->config['task_max_request']
        ]);
        foreach ($this->events as $event => $func) {
            if (method_exists($this, $func)) {
                $this->server->on($event, [$this, $func]);
            }
        }
        $this->server->start();
    }

    public function onReceive(\Swoole\Server $server)
    {

    }

    public function onWorkerStart(\Swoole\Server $server, $workerId)
    {
        if (function_exists('opcache_reset')) {
            opcache_reset();
        }
        swoole_set_process_name("demo:worker");
        if (!$server->taskworker) {
            ioc($this->handler)->onWorkerStart($server, $workerId);
        }
    }

    public function onTask(\Swoole\Server $server, $task_id, $reactorId, $data)
    {
//        Logger::getLogger('task')->info('on task');
        ioc($this->handler)->onTask($server, $data);
//        if (method_exists(ioc($this->handler), 'onTask')) {
//            ioc($this->handler)->onTask($server, $data);
//            return;
//        }
//
//        if ($data instanceof IJob) {
//            $data->handle();
//        } else {
//            $server->finish(is_string($data) ? $data : json_encode($data));
//        }
    }

    public function onFinish(\Swoole\Server $server, $task_id, string $data)
    {
        Logger::getLogger()->error("Task deal Error. id : $task_id", [$data]);
    }

    public function onStart(\Swoole\Server $server)
    {
        @file_put_contents('run.pid', $server->master_pid);
        swoole_set_process_name("demo:master");
    }

    public function onManagerStart(\Swoole\Server $server)
    {
        if (method_exists(ioc($this->handler), 'onManagerStart')) {
            ioc($this->handler)->onManagerStart($server);
        }
    }

}